//
//  BeautyRecommendViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/10.
//  美妆推荐

import UIKit

class BeautyRecommendViewController: QIBaseViewController {
    
    /// 预览图片
    var previewImg = UIImage()
    /// 原图在本地服务器地址
    var originalImgUrl = ""
    /// 原图地址
    var raw_file_path = ""
    /// 时间名称
    var event_name = ""
    /// 五官检测结果
    var wuGuanModel = QIFiveSensesResultModel() {
        didSet {
            getData()
        }
    }
    private var imgPreviewView = UIImageView()
    /// 底部展示推荐图片数组
    private var imgUrlArr = [String]()
    /// 更新试装使用
    private var Makeup_Transfer_Result_Local_Save_PathArr = [String]()
    /// 选择的推荐妆容
    private var selectIndex = 0
    /// 妆容json
    private var makeupDict = [String: String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "美妆推荐"
        
        addUI()
//        getData()
//        getFaceData()
        if wuGuanModel.top5_video_ID_list.count <= 0 || imgUrlArr.count <= 0{
            HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        }
    }
    

   
    private func addUI() {
        showGradientColor()
        
        imgPreviewView = UIImageView().then {
            $0.frame = CGRect(x: 15, y: NAV_HEIGHT, width: SCREEN_WIDTH - 30, height: 410)
            $0.image = previewImg
            $0.tag = 11
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 10)
        }
        view.addSubview(imgPreviewView)
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 15, y: imgPreviewView.bottom + 10, width: 100, height: 22)
            $0.text = "推荐妆容"
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL)
        
        collectionView.frame = CGRect(x: 0, y: titleL.bottom + 10, width: SCREEN_WIDTH, height: 100)
        view.addSubview(collectionView)
        
        let detailBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 60, y: collectionView.bottom + 20, width: 120, height: 36)
            $0.backgroundColor = ColorWithStr("#FFD5DA")
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("妆容详情", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 18)
            $0.addTarget(self, action: #selector(detailBtnClick), for: .touchUpInside)
        }
        view.addSubview(detailBtn)
        
        let advancedBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 50, y: detailBtn.bottom + 10, width: 100, height: 30)
            $0.titleLabel?.font = FONT(ofSize: 14)
            $0.setTitle("进阶选项", for: .normal)
            $0.setTitleColor(Color666666, for: .normal)
            $0.addTarget(self, action: #selector(advancedBtnClick), for: .touchUpInside)
        }
        view.addSubview(advancedBtn)
    }
    
    private func getFaceData() {
        
        let param = [
            "event_name": event_name,
            "raw_file_path": raw_file_path
        ]
        
        HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        let url = "http://124.222.206.164:3030/develop_facial_detection"
        QINetworkManager.requestJson(urlStr: url, parameters: param, isJson: true) { json in
//            print(json)
            self.wuGuanModel = json.dictionaryObject?.kj.model(QIFiveSensesResultModel.self) ?? QIFiveSensesResultModel()
            self.getData()
        }
    }
    
    private func getData() {
        if originalImgUrl.count > 0 {
            HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        }
        
        let url = "/Skin/makeup"
        let param = [
            "choose_video_code": wuGuanModel.top5_video_ID_list.joined(separator: ","),
            "event_name": event_name,
            "raw_file_path": raw_file_path,
            "facial_data_code_string": wuGuanModel.facial_data_code_string
        ]
        QINetworkManager.requestJson(urlStr: url, parameters: param) { json in
            print(json)
//            self.makeupJson = json
            let arr = json["Cos_Save_Path_Makeup_Transfer"].arrayValue
            self.imgUrlArr = arr.map { j in
                j.stringValue
            }
            let imgUrl = self.imgUrlArr[self.selectIndex]
            self.imgPreviewView.kf.setImage(with: URL(string: imgUrl))
            
            let arr1 = json["Makeup_Transfer_Result_Local_Save_Path"].arrayValue
            self.Makeup_Transfer_Result_Local_Save_PathArr = arr1.map { j in
                j.stringValue
            }
            self.makeupDict = [
                "Cos_Save_Path_Makeup_Transfer": self.imgUrlArr.first ?? "",
                "Makeup_Transfer_Result_Local_Save_Path": self.Makeup_Transfer_Result_Local_Save_PathArr.first ?? ""
            ]
            self.collectionView.reloadData()
        }
    }
    
    /// 妆容详情
    @objc private func detailBtnClick() {
        guard imgUrlArr.count > 0 else {
            ShowHUD(str: "请等待数据的返回")
            return
        }
        guard selectIndex > -1 else {
            ShowHUD(str: "请选择妆容")
            return
        }
        let videoCode = self.wuGuanModel.top5_video_ID_list[selectIndex]
        let titleStr = self.wuGuanModel.top5_makeup_type_chinese_name[selectIndex].joined(separator: "/")
        let vdict = self.wuGuanModel.top5_video_info_detail_dict[videoCode] as! [String: Any]
        let video_link = "\(vdict["视频链接"] ?? "")"
        
        QINetworkManager.requestJson(urlStr: "/Skin/video_details", parameters: nil) { json in
//            print(json)
            
            let vDataDict = json.dictionaryValue
            var mode = QIBeautyRecommenListModel()
            mode.title = titleStr
            mode.video_link = video_link
            if vDataDict.keys.contains(videoCode) {
                let j = vDataDict[videoCode]
                let m = j?.dictionaryObject?.kj.model(QIBeautyRecommenChildListModel.self) ?? QIBeautyRecommenChildListModel()
                mode.vModel = m
            }
            
            let ctl = FilterCriteriaVideoInfoViewController()
            ctl.event_name = self.event_name
            ctl.previewImg = self.imgPreviewView.image ?? self.previewImg
            ctl.originalImg = self.previewImg
            ctl.Local_Save_Path = self.Makeup_Transfer_Result_Local_Save_PathArr[self.selectIndex]
            ctl.videoCode = videoCode
            ctl.model = mode
            ctl.wuGuanModel = self.wuGuanModel
            ctl.raw_file_path = self.raw_file_path
            ctl.originalImgUrl = self.originalImgUrl
            ctl.makeupDict = self.makeupDict
            self.navigationController?.pushViewController(ctl, animated: true)
        }
        
    }
    
    /// 进阶选项
    @objc private func advancedBtnClick() {
        guard wuGuanModel.top5_video_info_detail_dict.count > 0 else {
            ShowHUD(str: "请等待数据的返回")
            return
        }
        let ctl = AdvancedBeautyViewController()
        ctl.previewImg = previewImg
        ctl.raw_file_path = raw_file_path
        ctl.wuGuanModel = wuGuanModel
        ctl.event_name = event_name
        ctl.originalImgUrl = originalImgUrl
        navigationController?.pushViewController(ctl, animated: true)
    }
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.scrollDirection = .horizontal
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.register(BeautyRecommendViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        return collectionView
    }()
}


extension BeautyRecommendViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 76, height: 100)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgUrlArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BeautyRecommendViewCell
        cell.imgUrl = imgUrlArr[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let imgUrl = imgUrlArr[indexPath.row]
        imgPreviewView.kf.setImage(with: URL(string: imgUrl))
        selectIndex = indexPath.row
        if self.imgUrlArr.count > indexPath.row && self.Makeup_Transfer_Result_Local_Save_PathArr.count > indexPath.row {
            self.makeupDict = [
                "Cos_Save_Path_Makeup_Transfer": self.imgUrlArr[indexPath.row],
                "Makeup_Transfer_Result_Local_Save_Path": self.Makeup_Transfer_Result_Local_Save_PathArr[indexPath.row]
            ]
        }
    }
    
}


class BeautyRecommendViewCell: UICollectionViewCell {
    
    private var imgView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        addUI()
    }
    
    private func addUI() {
        imgView = UIImageView().then {
            $0.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
            $0.image = UIImage(named: "")
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 5)
        }
        self.addSubview(imgView)
    }
    
    var imgUrl = "" {
        didSet {
            imgView.kf.setImage(with: URL(string: imgUrl))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
